package cl.orangepeople.whyem.portal.mockups.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cl.orangepeople.whyem.portal.backend.api.ClientDataService;
import cl.orangepeople.whyem.portal.backend.dto.client.ClientIDDTO;
import cl.orangepeople.whyem.portal.backend.dto.client.ClientIDData;
import cl.orangepeople.whyem.portal.backend.dto.client.ClientIDSearchBean;
import cl.orangepeople.whyem.portal.mockups.converter.RutConverter;
import cl.orangepeople.whyem.portal.service.whyemService;

import com.google.gson.Gson;

public class SearchClientDataServlet extends HttpServlet {
    private static Logger logger;
    private whyemService whyemService;
    private ClientDataService clientDataService;

    static {
	logger = LoggerFactory.getLogger(SearchClientDataServlet.class);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	whyemService = (whyemService) getBean("whyemService");
	
	String clientID = request.getParameter("clientID");
	logger.debug("Client id: {}", new Object[] { clientID });
	ClientIDSearchBean bean = new ClientIDSearchBean();
	
	Integer clientIDUnformatted = RutConverter.parseRut(clientID);
	
	if (ObjectUtils.notEqual(clientIDUnformatted, null)) {
	    if (!whyemService.existsUserInPortal(String.valueOf(clientIDUnformatted))) {
		clientDataService = (ClientDataService) getBean("clientDataService");
		
		ClientIDDTO clientData = new ClientIDDTO();
		clientData.setClientID(String.valueOf(clientIDUnformatted));
		bean = clientDataService.getClientData(clientData);
		request.getSession().setAttribute("clientID", clientIDUnformatted);
	    } else {
		bean.setReturnCode(-2);
		bean.setClientData(new ClientIDData());
	    }
	} else {
	    bean.setReturnCode(-1);
	    bean.setClientData(new ClientIDData());
	}
	
	Gson gson = new Gson();

	response.setContentType("text/plain; encoding=UTF-8");
	response.setCharacterEncoding("UTF-8");
	response.setHeader("Cache-Control", "no-store");
	response.setHeader("Pragma", "no-cache");
	response.setDateHeader("Expires", 0);
	response.getWriter().append(gson.toJson(bean));
    }
    
    protected Object getBean(String beanName) {
        WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
        return wac.getBean(beanName);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	doPost(req, resp);
    }
}